
package com.kim.pong.producer

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message
import org.spockframework.spring.SpringBean;
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.mock.mockito.MockBean
import spock.lang.Specification


@SpringBootTest
class ProducerSpec extends Specification {

    @Autowired
    Producer producer

    @SpringBean
    DefaultMQProducer defaultMQProducer = Mock()

    def "sendMessage should send two messages successfully"() {
        given:
        def message1 = new Message("Rate1", "Tag1", new Date().toString().getBytes())
        def message2 = new Message("Rate1", "Tag1", new Date().toString().getBytes())

        when:
        producer.sendMessage()

        then:
        0 * defaultMQProducer.start()
        0 * defaultMQProducer.send(message1) >> { new SendResult() }
        0 * defaultMQProducer.send(message2) >> { new SendResult() }
        0 * defaultMQProducer.shutdown()
    }

    def "sendMessage should handle exceptions"() {
        given:
        def message1 = new Message("Rate1", "Tag1", new Date().toString().getBytes())
        def message2 = new Message("Rate1", "Tag1", new Date().toString().getBytes())

        when:
        producer.sendMessage()

        then:
        0 * defaultMQProducer.start()
        0 * defaultMQProducer.send(message1) >> { throw new MQClientException("Error", null) }
        0 * defaultMQProducer.send(message2)
        0 * defaultMQProducer.shutdown()
    }
}